<?php

namespace app\index\controller;

use app\common\model\Ilike as IlikeModel;
use app\common\model\Mzongpai as MzongpaiModel;
use app\common\model\Manager as ManagerModel;
use app\common\model\Member as MemberModel;
use app\common\model\ZhMemberLog as ZhMemberLogModel;
use app\common\model\ManagerJob as ManagerJobModel;
use app\common\model\ManagerCompany as ManagerCompanyModel;
use app\common\model\ManagerPassword as ManagerPasswordModel;
use think\Db;

class Member extends Base
{
    /**
     * [getIndex  信徒列表]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function index()
    {
        $param = input('param.');
        $user = $this->user;
        $map = [];
        $this->getPageAndSize($param);
        $imodel = new IlikeModel;
        $zmodel = new MzongpaiModel;
        try{
            if(!empty($param['con'])){
                $map['am.tel|am.username'] = ['like', "%" . $param['con'] . "%"];
            }
            if(!empty($param['sex'])){
                $map['am.sex'] = $param['sex'];
            }
            if(!empty($param['start']) && !empty($param['end'])){
                $map['am.addtime'] = ['between',[strtotime($param['start']),strtotime($param['end'])]];
            }
            $map['i.itemid'] = $user['comid'];
            $map['i.status'] = 1;
            $count = $imodel->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $imodel->getList($map, $this->from, $this->size);
            foreach($lists as &$v){
                if(!empty($v['zid'])){
                    $zongpai = $zmodel->findData($v['zid'],'id','name');
                    $v['zongpai'] = $zongpai['name'];
                }else{
                    $v['zongpai'] = '无';
                }
                $v['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            }
        }catch (\Exception $e){
            systembug($e->getMessage(),3,$this->url);
            return admin_json(-1,$e->getMessage());
        }
        writelog($user['mid'],$user['comid'],'查看信徒列表');

        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getIndex  信徒列表]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getIndex()
    {
        $param = input('param.');
        $user = $this->user;
        $map = [];
        $this->getPageAndSize($param);
        $model = new ZhMemberLogModel;
        $mmodel = new MemberModel;
        $zmodel = new MzongpaiModel;
        try{
            $map['comid'] = $user['comid'];
            $count = $model->getCount($map);//满足条件的总数
            $allpage = intval(ceil($count / $this->size));//总页数
            $lists = $model->getlist($map, $this->from, $this->size,'id,mid');
            foreach($lists as &$v){
                $member = $mmodel->findData($v['mid'],'id','id,tel,username,sex,city,bathday,zid,addtime');
                if(!empty($member['zid'])){
                    $zongpai = $zmodel->findData($member['zid'],'id','name');
                    $v['zongpai'] = $zongpai['name'];
                }else{
                    $v['zongpai'] = '无';
                }
                $v['addtime'] = date('Y-m-d H:i:s',$member['addtime']);
                $v['id'] = $member['id'];
                $v['tel'] = $member['tel'];
                $v['username'] = $member['username'];
                $v['sex'] = $member['sex'];
                $v['city'] = $member['city'];
                $v['bathday'] = $member['bathday'];
            }
        }catch (\Exception $e) {
            systembug($e->getMessage(),3,$this->url);
            return admin_json(-1,$e->getMessage());
        }

        return admin_json(1, '获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getMe  获取个人信息]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function getMe()
    {
        $user = $this->user;
        $model = new ManagerModel;
        $mmodel = new MemberModel;
        $mpmodel = new ManagerPasswordModel;
        try{
            $manager = $model->findData($user['mid'],'id','id,username,tel,name');
            $member = $mmodel->findData($manager['tel'],'tel','username,img,sex,bathday');
            $mpss = $mpmodel->getOne(['comid'=>$user['comid'],'mid'=>$user['mid']]);
            $http = substr($member['img'],0,4);
            if($http != 'http'){
                $member['img'] = config('domain_name').$member['img'];
            }

            $data =array(
                'img' => $member['img'],
                'name' => $manager['name'],
                'fahao' => $manager['username'],
                'tel' => $manager['tel'],
                'sex' => $member['sex'],
                'bathday' => $member['bathday'],
                'jobid' => $mpss['jobid']
            );
        }catch (\Exception $e) {
            systembug($e->getMessage(),3,$this->url);
            return admin_json(-1,$e->getMessage());
        }
        writelog($user['mid'],$user['comid'],'查看个人信息');
        return admin_json(1,'获取成功',$data);
    }
    /**
     * [postEdit  修改个人信息]
     * @param
     * @return mixed|\think\response\Json
     * @author [C。]
     */
    public function postEdit()
    {
        $param = input('param.');
        $user = $this->user;
        $memodel = new MemberModel;
        $model = new ManagerModel;
        $mcmodel = new ManagerCompanyModel;
        $mpmodel = new ManagerPasswordModel;
        $map = [];
        try {
            $member = $memodel->findData($param['tel'],'tel','id');
            $map['tel'] = $param['tel'];
            $member_arr = array(
                'id' => $member['id'],
                'img' => $param['img'],
                'sex' => $param['sex'],
                'bathday' => $param['bathday']
            );
            $memodel->editData($member_arr);

            $manager_arr = array(
                'id' => $user['mid'],
                'name' => $param['name'],
                'username' => $param['username'],
            );
            $model->editData($manager_arr);

            $mcompany = $mcmodel->getOne(['mid'=>$user['mid'],'comid'=>$user['comid']],'id','id');
            $duty = array(
                'id'=>$mcompany['id'],
                'jobid' => $param['jobid']
            );
            $mcmodel->editData($duty);

            $mpassword = $mpmodel->getOne(['mid'=>$user['mid'],'comid'=>$user['comid']],'id','id');
            $duty = array(
                'id'=>$mpassword['id'],
                'jobid' => $param['jobid']
            );
            $mpmodel->editData($duty);
        } catch (\Exception $e) {
            systembug($e->getMessage(),3,$this->url);
            return admin_json(-1, $e->getMessage());
        }
        writelog($user['mid'],$user['comid'],'修改个人信息');
        return admin_json(1,'修改成功');
    }
    /**
     * [getCode 获取验证码]
     * @param
     * @author [C。]
     * @return json
     */
    public function postCode()
    {
        $param = input('param.');
        $tel = $param['tel'];
        $code = randString();
        $user = $this->user;
        $result = demo_sendsms($tel,$code);
        if ($result && 'OK' == $result['Code']) {
            $data = array(
                'tel' => $tel,
                'code' => $code,
                'type' => 4,
                'addtime' =>time()
            );
            Db::name('vercode')->insert($data);
            writelog($user['mid'],$user['comid'],'验证码发送成功'.$tel);
            return admin_json('1','验证码已发送');
        }else{
            writelog($user['mid'],$user['comid'],'验证码发送失败'.$tel);
            return admin_json('-1','请稍后再试！');
        }
    }
    /**
     * [postVeriTel 验证手机]
     * @param
     * @author [C。]
     * @return json
     */
    public function postVeriTel()
    {
        $param = input('param.');
        $user = $this->user;
        $map = [];
        $map['tel'] = $param['tel'];
        $map['code'] = $param['code'];
        $mem = Db::name('member')->where('tel',$param['tel'])->find();
        if(empty($mem)){
            writelog($user['mid'],$user['comid'],'手机号不存在！'.$param['tel']);
            return admin_json('-5', '手机号不存在！');
        }
        $result = Db::name('vercode')->where($map)->find();
        if(!empty($result)) {
            if (time() - $result['addtime'] > config('index.code_expiration_time')) {
                return admin_json('-2', '验证码已过期');
            }
            if ($result['status'] == 2) {
                return admin_json('-3', '验证码已使用');
            }
            Db::name('vercode')->where($map)->update(['status' => 2]);
        }else{
            writelog($user['mid'],$user['comid'],'手机号验证错误！'.$param['tel']);
            return admin_json('-1','手机号或验证码错误');
        }
        writelog($user['mid'],$user['comid'],'手机号验证成功！'.$param['tel']);
        return admin_json('1','验证成功');
    }
    /**
     * [postEdittel 换绑手机]
     * @param
     * @author [C。]
     * @return json
     */
    public function postEditTel()
    {
        $param = input('param.');
        $user = $this->user;
        $map = [];
        $map['tel'] = $param['tel'];
        $map['code'] = $param['code'];
        $mem = Db::name('member')->where('tel',$param['tel'])->find();
        if(!empty($mem)){
            return admin_json('-5', '该手机号已绑定用户！');
        }
        $result = Db::name('vercode')->where($map)->find();
        if(!empty($result)) {
            if (time() - $result['addtime'] > config('index.code_expiration_time')) {
                return admin_json('-2', '验证码已过期');
            }
            if ($result['status'] == 2) {
                return admin_json('-3', '验证码已使用');
            }
            Db::name('vercode')->where($map)->update(['status' => 2]);
        }else{
            return admin_json('-1','手机号或验证码错误');
        }
        $manager = Db::name('manager')->field('tel')->where('id',$user['mid'])->find();
        $member = Db::name('member')->field('id')->where('tel',$manager['tel'])->find();

        Db::name('manager')->where('id',$user['mid'])->update(['tel'=>$param['tel']]);
        Db::name('manager_password')->where('mid',$user['mid'])->update(['tel'=>$param['tel']]);

        $mresult = Db::name('member')->where('id',$member['id'])->update(['tel'=>$param['tel']]);
        if(!empty($mresult)){
            return admin_json('1','换绑成功');
        }else{
            return admin_json('-4','换绑失败');
        }
    }
}